import Axios from 'axios';
import Qs from 'qs';

export default () => {
    const baseURL = '';

    const readUserSessionData = (key) => {
        var jsonStr = window.sessionStorage.getItem('user') || null;
        if (jsonStr && key) {
            return JSON.parse(jsonStr)[key];
        } else {
            return jsonStr ? JSON.parse(jsonStr) : false;
        }
    };

    const axios = Axios.create({
        baseURL,
        timeout: 60 * 1000
    });

    axios.all = Axios.all;
    axios.spread = Axios.spread;

    axios.interceptors.request.use(
        (config) => {
            // console.log(config);
            // var token = readUserSessionData('token');
            // if (token) config.headers['Authentication-Token'] = token;

            switch (config.method) {
                case 'post':
                    config.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
                    break;
                case 'get':
                default:
                    config.headers.post['Content-Type'] = 'application/json;charset=utf-8';
                    break;
            }
            config.data = Qs.stringify(config.data);

            return config;
        },
        (error) => {
            return Promise.reject({
                type: 'error', event: 'console.print',
                location: 'axios-interceptors-request.error',
                result: error
            });
        }
    );

    axios.interceptors.response.use(
        (response) => {
            // console.log(response);
            return response.data;
        },
        (error) => {
            return Promise.reject({
                type: 'error', event: 'console.print',
                location: 'axios-interceptors-response.error',
                result: error
            });
        }
    );

    return axios;
};
